package com.zhijiang.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelDataListener<T> implements ReadListener<T> {

    /**
     * 批处理阈值，作用：减轻数据库的压力
     */
    private static final int BATCH_COUNT = 2;

    /**
     * 存储员工对象
     */
    List<T> list = new ArrayList<T>(BATCH_COUNT);

    @Override
    public void invoke(T data, AnalysisContext context) {

        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        list.stream().forEach(s -> log.info(String.valueOf(s)));
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        // 此方法能接住，在此匿名内部类的方法里抛出的异常，并进行处理，然后继续invoke方法。
        log.error("解析失败的原因:" + exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {

            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());

        }

    }
}
